﻿using RulesEngine.Models;

namespace RechargeRulesEngineSample;

public static class RuleResultTreeExtensions
{
    public static Dictionary<string, List<object>> GetOutputResults(this RuleResultTree resultTree)
    {
        var outputResults = new Dictionary<string, List<object>>();

        if (resultTree.IsSuccess)
        {
            if (resultTree.ActionResult?.Output != null)
            {
                var outputType = resultTree.Rule.Actions.OnSuccess.Context.GetValueOrDefault("type", "default") as string;
                if (!outputResults.ContainsKey(outputType))
                {
                    outputResults[outputType] = [];
                }
                outputResults[outputType].Add(resultTree.ActionResult.Output);
            }
        }

        if (resultTree.ChildResults != null)
        {
            var outputMode = resultTree.Rule.Properties?.GetValueOrDefault("nestedRuleOutputMode") as string;
            foreach (var childResult in resultTree.ChildResults)
            {
                var childOutputResults = GetOutputResults(childResult);

                foreach (var childOutputResult in childOutputResults)
                {
                    if (!outputResults.ContainsKey(childOutputResult.Key))
                    {
                        outputResults[childOutputResult.Key] = [];
                    }
                    outputResults[childOutputResult.Key].AddRange(childOutputResult.Value);
                }

                if (childOutputResults.Any() && outputMode == "one")
                {
                    break;
                }
            }
        }

        return outputResults;
    }
}
